<?php
/*
 +----------------------------------------------------------------------
 + Title        : WechatService 控制器
 + Author       : Randy_chen
 + Version      : V1.0.0.1
 + Initial-Time : 2023/5/14 7:10
 + Last-time    : 2023/5/14 7:10+ chen2
 + Desc         : WechatService
 +----------------------------------------------------------------------
*/


namespace app\common\service;

use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\MiniApp\Application;

class WechatService
{
    protected $app;

    /**
     * @throws InvalidArgumentException
     */
    public function __construct()
    {
        $config = [
            'app_id'         => config("app.wechat.appid"),
            'mch_id'         => config("app.wechat.mch_id"),
            'secret_key'     => config("app.wechat.secret"),
            // 商户证书
            'private_key'    => __DIR__.'/certs/apiclient_key.pem',
            'certificate'    => __DIR__.'/certs/apiclient_cert.pem',
            /**
             * 接口请求相关配置，超时时间等，具体可用参数请参考：
             * https://github.com/symfony/symfony/blob/5.3/src/Symfony/Contracts/HttpClient/HttpClientInterface.php
             */
            'http'           => [
                'throw'   => false, // 状态码非 200、300 时是否抛出异常，默认为开启
                'timeout' => 5.0,
                // 'base_uri' => 'https://api.mch.weixin.qq.com/', // 如果你在国外想要覆盖默认的 url 的时候才使用，根据不同的模块配置不同的 uri
            ],
        ];
        $this->app = new Application($config);
    }

    /**
     * 通过微信code获取openid和sessionId
     * @author : Randy_chen
     * @Date: 2023/5/14
     * @Time: 7:19
     */
    public function codeToSession($code){
        $utils = $this->app->getUtils();
        $response = $utils->codeToSession($code);
        return $response;
    }
}